package org.yray.tts.media;

import lombok.extern.slf4j.Slf4j;
import org.yray.tts.tx.TtsReqParams;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Slf4j
public class MediaReadTss {

    private static String url="http://172.168.198.20:9080/tts.cgi";

    public static byte[] readBytes(String text,int format)
    {
        byte[] result=null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            OutputStream outputStream = connection.getOutputStream();
            TtsReqParams ttsReqParams = new TtsReqParams("1", text, 0.0F, "101007", 8);
            String content = ttsReqParams.toJsonStr();
            log.info("text={}", content);
            // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
            connection.getOutputStream().write(content.getBytes());
            outputStream.flush();
            outputStream.close();
            InputStream reader = connection.getInputStream();
            byte[] b = new byte[10240];
            int len = 0;
            ByteBuf byteBuf=new ByteBuf();
            while ((len = reader.read(b, 0, 10240)) != -1) {
                byteBuf.addBytes(b,0,len);
            }
            result=byteBuf.toBytes();
            reader.close();
            connection.disconnect();
        }catch (Exception e)
        {
            log.error(e.getMessage());
        }
        return result;
    }
}
